# 导入请求
import requests
import lxml.html
import time
#获取验证码的url, 一般指登录页面
loginUrl = 'http://exercise.kingname.info/exercise_captcha.html'

# 登录方法
login_url = 'http://exercise.kingname.info/exercise_captcha_check'

saveImage = 'captcha.jpg'
# 获取图片验证码
def getImageCode (session,codeUrl,saveFilePath):
    print(f' 登录页面地址: {codeUrl}')
    codeContent = session.get(codeUrl).content.decode()
    selector = lxml.html.fromstring(codeContent)
    captcha_url = selector.xpath('//img/@src')[0]
    imageUrl = 'http://exercise.kingname.info/' + captcha_url
    image = requests.get(imageUrl).content
    # 获取内容，以图片方式进行保存
    with open(saveFilePath,'wb') as f:
        f.write(image)
        print(f'保存到路径: {saveFilePath}')
    return getCodeByCjyWithUrl(saveFilePath)

# 根据超级鹰获取图片验证码,通过 本地图片
def getCodeByCjyWithUrl(saveFilePath):
    api_url = "http://upload.chaojiying.net/Upload/Processing.php"
    # 读取图片
    with open(saveFilePath, 'rb') as f:
        image_data = f.read()
    # 构造请求参数
    payload = {
        'user': 'yueshushu',
        'pass': 'yjl1314cjy',
        'softid': '0f1aad8b4659e731c672f3024e89b5cd',
        'codetype': 1004  # 识别类型，1004 表示纯数字
    }

    # 发送 POST 请求
    files = {'userfile': (saveImage, image_data)}
    response = requests.post(api_url, data=payload, files=files)
    print(f'获取请求结果: {response.content.decode()}')
    # 检查响应
    if response.status_code == 200:
        result = response.json()
        if result['err_no'] == 0:
            return result['pic_str']
        else:
            print(f"识别失败：{result['err_msg']}")
            return None
    else:
        print(f"请求失败，状态码：{response.status_code}")
        return None

# 获取到验证码, 要使用session
session = requests.Session()
captcha = getImageCode(session,loginUrl,saveImage)
print(f'\n 获取验证码: {captcha} \n')
data = {
    'captcha': captcha
}
loginResponse = session.post(login_url,data= data)
print(f'输入验证码之后，网站返回 {loginResponse.content.decode()}')